import { defineStore } from "pinia";
import { ref, computed } from "vue";
import type { User, PageQuery } from "@/types";
import {
  getUsersByOrganize,
  createUser,
  updateUser,
  deleteUser,
  $exportUsers,
  importUsers,
  toggleUserStatus,
} from "@/api/user";
import { success } from "@/utils/toast";

export const useUserStore = defineStore("user", () => {
  // 状态
  const userList = ref<User[]>([]);
  const originalUserList = ref<User[]>([]); // 存储原始用户数据，用于本地筛选
  const selectedUsers = ref<User[]>([]);
  const currentUser = ref<User | null>(null);
  const loading = ref(false);
  const searchKeyword = ref("");
  const selectedOrganizeId = ref<number>(0);

  // 分页状态
  const pagination = ref({
    currentPage: 1,
    pageSize: 20,
    total: 0,
    pageSizes: [10, 20, 50, 100],
    layout: "total, sizes, prev, pager, next, jumper",
    background: true,
    handleSizeChange: (size: number) => {
      pagination.value.pageSize = size;
      pagination.value.currentPage = 1;
      fetchUserList();
    },
    handleCurrentChange: (page: number) => {
      pagination.value.currentPage = page;
      fetchUserList();
    },
  });

  // 计算属性
  const hasSelectedUsers = computed(() => selectedUsers.value.length > 0);
  const selectedUserIds = computed(() =>
    selectedUsers.value.map((user) => Number(user.id))
  );

  /**
   * 获取用户列表
   */
  const fetchUserList = async (params?: {
    page?: number;
    pageSize?: number;
  }) => {
    if (!selectedOrganizeId.value) {
      userList.value = [];
      pagination.value.total = 0;
      return;
    }

    try {
      loading.value = true;
      const queryParams: PageQuery = {
        page: params?.page || pagination.value.currentPage,
        pageSize: params?.pageSize || pagination.value.pageSize,
        // 不再传递keyword，因为使用本地筛选
      };

      const response = await getUsersByOrganize(
        selectedOrganizeId.value,
        queryParams
      );
      // 尝试不同的数据访问方式
      let fetchedUsers = [];
      let total = 0;
      let currentPage = 1;
      let pageSize = 20;

      if (response.data) {
        // 如果response.data是数组，直接使用
        if (Array.isArray(response.data)) {
          fetchedUsers = response.data;
        }
        // 如果response.data有data属性，使用data
        else if (response.data.data && Array.isArray(response.data.data)) {
          fetchedUsers = response.data.data;
          total = response.data.total || 0;
          currentPage = response.data.page || 1;
          pageSize = response.data.pageSize || 20;
        }
        // 如果response.data有list属性，使用list
        else if (
          (response.data as any).list &&
          Array.isArray((response.data as any).list)
        ) {
          fetchedUsers = (response.data as any).list;
          total = response.data.total || (response.data as any).count || 0;
          currentPage =
            response.data.page || (response.data as any).currentPage || 1;
          pageSize =
            response.data.pageSize || (response.data as any).size || 20;
        }
      }

      console.log("解析后的用户数据:", fetchedUsers);
      console.log(
        "分页信息 - total:",
        total,
        "currentPage:",
        currentPage,
        "pageSize:",
        pageSize
      );

      originalUserList.value = fetchedUsers; // 保存原始数据
      userList.value = fetchedUsers;
      pagination.value.total = total;
      pagination.value.currentPage = currentPage;
      pagination.value.pageSize = pageSize;

      console.log("设置后的分页信息:", pagination.value);
    } catch (error) {
      console.error("获取用户列表失败:", error);
    } finally {
      loading.value = false;
    }
  };

  /**
   * 创建用户
   */
  const createUserAction = async (userData: Partial<User>) => {
    try {
      loading.value = true;
      const response = await createUser(userData);
      success("用户创建成功");
      await fetchUserList();
      return response.data;
    } catch (error) {
      console.error("创建用户失败:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 更新用户
   */
  const updateUserAction = async (userData: Partial<User>) => {
    try {
      loading.value = true;
      const response = await updateUser(userData);
      success("用户更新成功");
      await fetchUserList();
      return response.data;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 删除用户
   */
  const deleteUserAction = async (id: number) => {
    try {
      loading.value = true;
      await deleteUser(id);
      success("用户删除成功");
      await fetchUserList();
    } catch (error) {
      console.error("删除用户失败:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 批量删除用户
   */
  const batchDeleteUsersAction = async (ids: number[]) => {
    try {
      loading.value = true;

      // 循环调用单个删除接口
      for (const id of ids) {
        await deleteUser(id);
      }

      success(`成功删除 ${ids.length} 个用户`);
      selectedUsers.value = [];
      await fetchUserList();
    } catch (error) {
      console.error("批量删除用户失败:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 切换用户状态
   */
  const toggleUserStatusAction = async (id: number, isEnable: boolean) => {
    try {
      const response = await toggleUserStatus(id, isEnable);
      if (response.success || response.code === 200) {
        success("状态更新成功");
        await fetchUserList();
      }
    } catch (error) {
      console.error("更新用户状态失败:", error);
      throw error;
    }
  };

  /**
   * 导出用户
   */
  const exportUsersAction = async (params?: { organizeId?: number }) => {
    const response = await $exportUsers();
    return response;
  };

  /**
   * 导入用户
   */
  const importUsersAction = async (file: File) => {
    try {
      loading.value = true;
      const response = await importUsers(file);
      if (response.success || response.code === 200) {
        success(
          `导入成功：${response.data.success}条，失败：${
            (response.data as any).failed || 0
          }条`
        );
        await fetchUserList();
        return response.data;
      }
    } catch (error) {
      console.error("导入用户失败:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 搜索用户 - 本地筛选
   */
  const searchUsers = (keyword: string) => {
    searchKeyword.value = keyword;
    pagination.value.currentPage = 1;

    if (!keyword.trim()) {
      // 如果搜索关键词为空，显示所有用户
      userList.value = originalUserList.value;
    } else {
      // 本地筛选用户
      userList.value = originalUserList.value.filter((user) => {
        const searchText = keyword.toLowerCase();
        return (
          user.name?.toLowerCase().includes(searchText) ||
          user.eMail?.toLowerCase().includes(searchText) ||
          user.phone?.toLowerCase().includes(searchText)
        );
      });
    }

    // 更新分页总数
    pagination.value.total = userList.value.length;
  };

  /**
   * 设置选中的组织ID
   */
  const setSelectedOrganizeId = (organizeId: number) => {
    selectedOrganizeId.value = organizeId;
    pagination.value.currentPage = 1;
    searchKeyword.value = "";
    selectedUsers.value = [];
    originalUserList.value = []; // 清空原始数据
  };

  /**
   * 设置选中的用户
   */
  const setSelectedUsers = (users: User[]) => {
    selectedUsers.value = users;
  };

  /**
   * 设置当前用户
   */
  const setCurrentUser = (user: User | null) => {
    currentUser.value = user;
  };

  /**
   * 更新分页
   */
  const updatePagination = (page: number, pageSize?: number) => {
    pagination.value.currentPage = page;
    if (pageSize) {
      pagination.value.pageSize = pageSize;
    }
    fetchUserList();
  };

  /**
   * 重置状态
   */
  const resetState = () => {
    userList.value = [];
    originalUserList.value = [];
    selectedUsers.value = [];
    currentUser.value = null;
    searchKeyword.value = "";
    selectedOrganizeId.value = 0;
    pagination.value = {
      currentPage: 1,
      pageSize: 20,
      total: 0,
      pageSizes: [10, 20, 50, 100],
      layout: "total, sizes, prev, pager, next, jumper",
      background: true,
      handleSizeChange: (size: number) => {
        pagination.value.pageSize = size;
        pagination.value.currentPage = 1;
        fetchUserList();
      },
      handleCurrentChange: (page: number) => {
        pagination.value.currentPage = page;
        fetchUserList();
      },
    };
  };

  return {
    // 状态
    userList,
    originalUserList,
    selectedUsers,
    currentUser,
    loading,
    searchKeyword,
    selectedOrganizeId,
    pagination,

    // 计算属性
    hasSelectedUsers,
    selectedUserIds,

    // 方法
    fetchUserList,
    createUserAction,
    updateUserAction,
    deleteUserAction,
    batchDeleteUsersAction,
    toggleUserStatusAction,
    exportUsersAction,
    importUsersAction,
    searchUsers,
    setSelectedOrganizeId,
    setSelectedUsers,
    setCurrentUser,
    updatePagination,
    resetState,
  };
});
